import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.MessageToMessageDecoder
import java.nio.charset.StandardCharsets

// 自定义行解码器 - 每次只提取一条消息
class TcpMessageDecoder : MessageToMessageDecoder<ByteBuf>() {

    private val lineSeparator = "\r\n".toByteArray(charset("GBK"))
    private val lineSeparatorLength = lineSeparator.size
    private val buffer = StringBuilder()

    override fun decode(ctx: ChannelHandlerContext, buf: ByteBuf, out: MutableList<Any>) {
        // 将新数据追加到缓冲区
        val bytes = ByteArray(buf.readableBytes())
        buf.readBytes(bytes)
        buffer.append(String(bytes,charset("GBK")))

        // 查找第一条完整消息
        val endIndex = findLineSeparator(0)
        if (endIndex != -1) {
            // 提取消息并添加到输出列表
            val message = buffer.substring(0, endIndex)
            out.add(message)

            // 移除已处理的数据
            buffer.delete(0, endIndex + lineSeparatorLength)
        }
    }

    private fun findLineSeparator(startIndex: Int): Int {
        var i = startIndex
        while (i <= buffer.length - lineSeparatorLength) {
            var match = true
            for (j in lineSeparator.indices) {
                if (buffer[i + j] != lineSeparator[j].toChar()) {
                    match = false
                    break
                }
            }
            if (match) {
                return i
            }
            i++
        }
        return -1
    }
}